package com.things8.iot.common.aop;

import com.things8.iot.common.enums.GlobalResultEnum;
import com.things8.iot.common.result.GlobalException;
import com.things8.iot.common.result.GlobalResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/5/9 15:55
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler
    public GlobalResult handle(MethodArgumentNotValidException exception) {
        return GlobalResult.fail(GlobalResultEnum.PARAM_ERROR.getCode(),
                exception.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(",")));
    }

    @ExceptionHandler
    public GlobalResult handle(ConstraintViolationException exception) {
        return GlobalResult.fail(GlobalResultEnum.PARAM_ERROR.getCode(),
                exception.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(",")));
    }

    @ExceptionHandler
    public GlobalResult handle(GlobalException exception) {
        log.error("全局抛出异常捕获:{}", exception.toString());
        return GlobalResult.fail(exception.getCode(), exception.getMsg());
    }

}